<template>
  <div class="mine-container">
    
    <!-- 用户信息头部 -->
    <div class="user-header">
      <div class="user-info">
        <div class="avatar-container">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="用户头像" class="user-avatar">
          <i v-else class="el-icon-picture-outline"></i>
          <div v-if="!userInfo.avatar" class="avatar-text">暂时无法查看</div>
        </div>
        <div class="user-id">{{ userInfo.nickName }}</div>
        <div class="recharge-amount">账户余额: {{ userInfo.balance }}元</div>
      </div>
      <div class="city-skyline"></div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="menu-list">
        <div class="menu-item" v-for="(item, index) in menuItems" :key="index" @click="handleMenuClick(item)">
          <span class="menu-text">{{ item.text }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
    </div>

    <!-- 个人信息弹窗 -->
    <el-dialog
      title="个人信息"
      :visible.sync="personalInfoDialogVisible"
      width="90%"
      :close-on-click-modal="false"
      custom-class="personal-info-dialog"
      @open="handleDialogOpen"
    >
      <div class="personal-info-form">
        <div class="form-item">
          <label class="form-label">姓名</label>
          <el-input
            v-model="personalInfoForm.nickName"
            placeholder="请输入姓名"
            maxlength="20"
            show-word-limit
            clearable
          ></el-input>
        </div>
        
        <div class="form-item">
          <label class="form-label">性别</label>
          <el-radio-group v-model="personalInfoForm.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
        </div>        
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="savePersonalInfo" :loading="saveLoading">保存</el-button>
      </div>
    </el-dialog>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <div class="nav-item" :class="{ active: currentTab === 'home' }" @click="switchTab('home')">
        <i class="el-icon-house"></i>
        <span>首页</span>
      </div>
      <div class="nav-item" :class="{ active: currentTab === 'scan' }" @click="switchTab('scan')">
        <i class="el-icon-camera"></i>
        <span>扫码用电</span>
      </div>
      <div class="nav-item active" :class="{ active: currentTab === 'mine' }" @click="switchTab('mine')">
        <i class="el-icon-user"></i>
        <span>我的</span>
      </div>
    </div>

  </div>
</template>

<script>
import { getUserProfile, updateUserProfile } from '@/api/system/user'

export default {
  name: 'Mine',
  data() {
    return {
      currentTab: 'mine',
      userInfo: {},
      menuItems: [
        { text: '个人信息', action: 'personalInfo' },
        //{ text: '续费', action: 'renewal' },
        { text: '账单查询', action: 'billQuery' },
        { text: '我的预约', action: 'myAppointments' }
      ],
      personalInfoDialogVisible: false,
      personalInfoForm: {
        nickName: '',
        sex: '',
        phonenumber: '',
        email: ''
      },
      saveLoading: false,
      avatarUrl: '' // 新增头像URL
    }
  },
  created() {
    this.getUserProfile()
  },
  methods: {
    getUserProfile() {
      getUserProfile().then(res => {
        this.userInfo = res.data
        this.personalInfoForm = { ...this.personalInfoForm, ...res.data }
        this.avatarUrl = res.data.avatar // 初始化头像URL
      })
    },
    handleMenuClick(item) {
      console.log('点击菜单项:', item.text, item.action)
      // 这里可以添加具体的业务逻辑
      if (item.action === 'personalInfo') {
        this.personalInfoDialogVisible = true
      } else if (item.action === 'renewal') {
        this.$message.info(`${item.text}功能开发中`)
      } else if (item.action === 'billQuery') {
        this.$router.push('/wechat/mybills')
      } else if (item.action === 'myAppointments') {
        this.$message.info(`${item.text}功能开发中`)
      }      
    },
    // 扫码
    scanQRCode() {
      wx.scanQRCode({
        needResult: 1,
        scanType: ['qrCode', 'barCode'],
        success: (result) => {
            window.meterNo = result.resultStr
            this.$router.push('/wechat/recharge')
        },
        fail: (error) => {
           this.$message.error("扫码失败")
        }
      })
      this.currentTab = 'mine'
    },
    switchTab(tab) {
        this.currentTab = tab
        if (tab === 'home') {
            this.$router.push('/wechat/index')
        } else if (tab === 'mine') {
            this.$router.push('/wechat/mine')
        } else if (tab === 'scan') {
            this.scanQRCode()
        } 
    },
    savePersonalInfo() {
      // 表单验证
      if (!this.personalInfoForm.nickName || this.personalInfoForm.nickName.trim() === '') {
        this.$message.warning('请输入姓名')
        return
      }
      
      if (this.personalInfoForm.nickName.trim().length < 2) {
        this.$message.warning('姓名长度不能少于2个字符')
        return
      }
      
      this.saveLoading = true
      
      // 准备提交的数据
      const submitData = {
        nickName: this.personalInfoForm.nickName.trim(),
        sex: this.personalInfoForm.sex
      }
      
      updateUserProfile(submitData).then(res => {
        if (res.code === 200) {
          this.$message.success('个人信息保存成功')
          // 更新本地用户信息
          this.userInfo = { ...this.userInfo, ...submitData }
          this.personalInfoDialogVisible = false
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      }).catch(err => {
        console.error('保存个人信息失败:', err)
        this.$message.error('保存失败，请稍后重试')
      }).finally(() => {
        this.saveLoading = false
      })
    },
    handleDialogOpen() {
      // 弹窗打开时，清空表单，但保留用户信息
      this.personalInfoForm = { ...this.personalInfoForm, ...this.userInfo }
      this.avatarUrl = this.userInfo.avatar // 弹窗打开时也更新头像URL
    },
    cancelEdit() {
      this.personalInfoDialogVisible = false
    },
    triggerAvatarUpload() {
      this.$refs.avatarInput.click()
    },
    handleAvatarChange(event) {
      const file = event.target.files[0]
      if (file) {
        // 文件大小验证（限制为2MB）
        if (file.size > 2 * 1024 * 1024) {
          this.$message.warning('头像文件大小不能超过2MB')
          return
        }
        
        // 文件格式验证
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
        if (!allowedTypes.includes(file.type)) {
          this.$message.warning('只支持JPG、PNG、GIF格式的图片')
          return
        }
        
        // 预览图片
        const reader = new FileReader()
        reader.onload = (e) => {
          this.avatarUrl = e.target.result
          this.$message.success('头像预览成功，请点击保存按钮保存更改')
        }
        reader.onerror = () => {
          this.$message.error('图片读取失败，请重试')
        }
        reader.readAsDataURL(file)
      }
      
      // 清空input值，允许重复选择同一文件
      event.target.value = ''
    }
  }
}
</script>

<style scoped>
.mine-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 顶部状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.status-left, .status-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-center {
  text-align: center;
}

.status-center .title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.status-center .url {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.time {
  font-size: 14px;
  color: #333;
}

.battery {
  font-size: 12px;
  color: #333;
}

/* 用户信息头部 */
.user-header {
  background: linear-gradient(135deg, #4a90e2, #357abd);
  color: white;
  padding: 20px 15px;
  position: relative;
  overflow: hidden;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.user-info {
  text-align: center;
  position: relative;
  z-index: 2;
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto 15px;
}

.avatar-container i {
  font-size: 24px;
  margin-bottom: 5px;
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-text {
  font-size: 10px;
  text-align: center;
  line-height: 1.2;
}

.user-id {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.recharge-amount {
  font-size: 16px;
  opacity: 0.9;
}

.city-skyline {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(transparent, rgba(255, 255, 255, 0.1));
  opacity: 0.3;
}

/* 主内容区域 */
.main-content {
  background-color: #fff;
  margin: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.menu-list {
  padding: 0;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:hover {
  background-color: #f8f9fa;
}

.menu-text {
  font-size: 16px;
  color: #333;
}

.menu-item i {
  color: #ccc;
  font-size: 16px;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding:  0;
}

.nav-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;
  transition: color 0.2s;
}

.nav-item i {
  font-size: 20px;
  margin-bottom: 4px;
  color: #999;
}

.nav-item span {
  font-size: 12px;
  color: #999;
}

.nav-item.active i,
.nav-item.active span {
  color: #4a90e2;
}

.nav-item.active i {
  background-color: #4a90e2;
  color: white;
  border-radius: 50%;
  padding: 8px;
  margin-bottom: 4px;
}

/* 个人信息弹窗样式 */
.personal-info-dialog .el-dialog__body {
  padding: 20px 30px;
}

.personal-info-form .form-item {
  margin-bottom: 20px;
}

.personal-info-form .form-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.avatar-item .avatar-upload {
  display: flex;
  justify-content: center;
}

.avatar-preview {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #e0e0e0;
  transition: all 0.3s;
}

.avatar-preview:hover {
  border-color: #4a90e2;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #ccc;
  background-color: #f5f5f5;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay i {
  font-size: 20px;
  margin-bottom: 4px;
}

.avatar-overlay span {
  font-size: 12px;
}

.personal-info-form .el-input,
.personal-info-form .el-radio-group {
  width: 100%;
}

.personal-info-form .form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.personal-info-form .dialog-footer {
  text-align: right;
}

/* 移动端弹窗样式优化 */
@media (max-width: 768px) {
  .personal-info-dialog .el-dialog {
    margin: 5vh auto !important;
    width: 95% !important;
  }
  
  .personal-info-dialog .el-dialog__body {
    padding: 15px 20px;
  }
  
  .personal-info-form .form-item {
    margin-bottom: 15px;
  }
  
  .personal-info-form .form-label {
    font-size: 13px;
    margin-bottom: 6px;
  }
  
  .personal-info-form .el-radio {
    margin-right: 20px;
  }
  
  .dialog-footer .el-button {
    padding: 8px 20px;
    font-size: 14px;
  }
}

/* 移动端弹窗样式优化 */
@media (max-width: 768px) {
  .personal-info-dialog .el-dialog {
    margin: 5vh auto !important;
    width: 95% !important;
  }
  
  .personal-info-dialog .el-dialog__body {
    padding: 15px 20px;
  }
  
  .personal-info-form .form-item {
    margin-bottom: 15px;
  }
  
  .personal-info-form .form-label {
    font-size: 13px;
    margin-bottom: 6px;
  }
  
  .personal-info-form .el-radio {
    margin-right: 20px;
  }
  
  .dialog-footer .el-button {
    padding: 8px 20px;
    font-size: 14px;
  }
}


/* 响应式设计 */
@media (max-width: 375px) {
  .user-header {
    padding: 15px 10px;
  }
  
  .header-title {
    font-size: 20px;
  }
  
  .avatar-container {
    width: 70px;
    height: 70px;
  }
  
  .menu-item {
    padding: 15px 12px;
  }
}
</style>
